import { useState } from "react";
import { Popover, Tooltip, Checkbox } from "antd";
import type { CheckboxChangeEvent } from "antd/es/checkbox";
import type {
  CheckboxOptionType,
  CheckboxValueType,
} from "antd/es/checkbox/Group";
import { SvgIcon } from "@/components/SvgIcon";
import styles from "./index.module.less";

const CheckboxGroup = Checkbox.Group;

export interface FilterProps {
  options: CheckboxOptionType[];
  defaultCheckedList?: CheckboxValueType[];
  onChange: FcProps;
}
export const Filter = ({
  options = [],
  defaultCheckedList = options.map((option) => option.value),
  onChange,
}: FilterProps) => {
  const getIndeterminate = (list: CheckboxValueType[]) =>
    !!list.length && list.length < options.length;
  const getCheckAll = (list: CheckboxValueType[]) =>
    list.length === options.length;
  const allKeys = options.map((option) => option.value);
  const [prevDefaultCheckedList, setPrevDefaultCheckedList] =
    useState(defaultCheckedList);
  const [checkedList, setCheckedList] =
    useState<CheckboxValueType[]>(defaultCheckedList);

  if (
    JSON.stringify(prevDefaultCheckedList) !==
    JSON.stringify(defaultCheckedList)
  ) {
    setPrevDefaultCheckedList(defaultCheckedList);
    setCheckedList(defaultCheckedList);
  }
  const [indeterminate, setIndeterminate] = useState(
    getIndeterminate(defaultCheckedList)
  );
  const [checkAll, setCheckAll] = useState(getCheckAll(defaultCheckedList));

  const onCheckChange = (list: CheckboxValueType[]) => {
    setCheckedList(list);
    setIndeterminate(getIndeterminate(list));
    setCheckAll(getCheckAll(list));
    onChange?.(list);
  };

  const onCheckAllChange = (e: CheckboxChangeEvent) => {
    setCheckedList(e.target.checked ? allKeys : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
    onChange?.(e.target.checked ? allKeys : []);
  };
  return (
    <>
      <Tooltip title="列设置">
        <Popover
          placement="bottomRight"
          trigger={"click"}
          title={
            <Checkbox
              indeterminate={indeterminate}
              onChange={onCheckAllChange}
              checked={checkAll}
            >
              全选
            </Checkbox>
          }
          content={
            <CheckboxGroup
              options={options}
              value={checkedList}
              onChange={onCheckChange}
            />
          }
          overlayClassName={styles.popover}
        >
          <SvgIcon name="filter" className={styles["filter-icon"]} />
        </Popover>
      </Tooltip>
    </>
  );
};
